package com.celebriosoftware.client.fragments;

import android.annotation.TargetApi;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.celebriosoftware.celebrioclient.R;
import com.celebriosoftware.client.JavaScriptInterface;
import com.celebriosoftware.client.MainActivity;

//This fragment loads main celebrio website into webview, and either displays a login page, or, if already logged in,
//is redirected to page that trashes this and starts desktop fragment instead
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class LoginFragment extends Fragment {
	private MainActivity mainActivity;
	private WebView engine; //webview in which login screen runs

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mainActivity=(MainActivity) this.getActivity();
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.login_screen, container, false);
	}
	
	@Override
	public void onStart() {
		super.onStart();
		engine = (WebView) getView().findViewById(R.id.web_engine);
		prepareEngine();
 		engine.addJavascriptInterface(new JavaScriptInterface((MainActivity)mainActivity, engine), "Android");
 		engine.loadUrl(MainActivity.CELEBRIO_URL);
	}
	
	private void prepareEngine() {
		engine.getSettings().setRenderPriority(RenderPriority.HIGH);
		engine.getSettings().setJavaScriptEnabled(true);
		engine.getSettings().setDatabaseEnabled(true);
		engine.getSettings().setDatabasePath("/data/data/com.celebriosoftware.client/databases"); 
		engine.getSettings().setSupportZoom(false);
		engine.getSettings().setDefaultZoom(WebSettings.ZoomDensity.FAR);
		engine.getSettings().setGeolocationEnabled(true);
		engine.getSettings().setGeolocationDatabasePath(
				"/data/data/com.celebriosoftware.client/databases");
		
		String clientVersion = "unknown";	
		try
		{
			clientVersion = mainActivity.getPackageManager().getPackageInfo(mainActivity.getPackageName(), 0).versionName;
		}
		catch (NameNotFoundException e)
		{
		    Log.e("Celebrio-Version", e.getMessage());
		}
		
		DisplayMetrics metrics = engine.getResources().getDisplayMetrics();
		String userAgent = engine.getSettings().getUserAgentString();
		
		userAgent = userAgent.replaceFirst("(\\))", "; " + MainActivity.CELEBRIO_CLIENT
				+ "/" + clientVersion + "; dpi/" + metrics.densityDpi
				+ "; res-width/" + metrics.widthPixels + "; res-height/"
				+ metrics.heightPixels + ")");
	
		Log.i("Celebrio-UserAgent", userAgent);
		engine.getSettings().setUserAgentString(userAgent);
		engine.setWebViewClient(new WebViewClient() {
			
			@Override
			public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
				if(errorCode==ERROR_HOST_LOOKUP || errorCode==ERROR_CONNECT || errorCode==ERROR_TIMEOUT) {
					mainActivity.lastUri=failingUrl;
					mainActivity.startPeriodicNetworkChecking();
				}
				Log.i("errorCode", ((Integer)errorCode).toString());
				Log.i("errorDescription", description);
				Log.i("errorUrl",  failingUrl);
			}
			
			@Override
			public void onPageFinished(WebView view, String url) {
				if(isVisible()) {
					mainActivity.removeSplashScreen();
				}
				Log.i("page FINISHED", "in login: "+url);
			}
			
			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				mainActivity.showSplashScreen();
				Log.i("page STARTED", "in login: "+url);
			}
		});
		
		engine.setWebChromeClient(new MyWebChromeClient());
	}
	
	class MyWebChromeClient extends WebChromeClient {
		@Override
		public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
			callback.invoke(origin, true, false);
		}    
	}
}
